package com.riteny.config;

import com.riteny.grant.phoneverifycode.PhoneVerifyCodeDetailsAuthenticationProvider;
import com.riteny.grant.phoneverifycode.PhoneVerifyCodeTokenGranter;
import com.riteny.grant.phoneverifycode.PhoneVerifyCodeUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenGranter;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeTokenGranter;
import org.springframework.security.oauth2.provider.implicit.ImplicitTokenGranter;
import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter;
import org.springframework.security.oauth2.provider.refresh.RefreshTokenGranter;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableAuthorizationServer
public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    private PhoneVerifyCodeUserDetailsService phoneVerifyCodeUserDetailsService;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        oauthServer
                .realm("oauth2-resources")
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()")
                .allowFormAuthenticationForClients();
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.authenticationManager(authenticationManager)
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
                .tokenStore(new InMemoryTokenStore())
                .tokenGranter(tokenGranter(endpoints));
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        // 默认使用内存，这里配置使用数据库
        clients.jdbc(dataSource);
    }

    private TokenGranter tokenGranter(AuthorizationServerEndpointsConfigurer endpoints) {
        List<TokenGranter> list = new ArrayList<>();

        list.add(new ResourceOwnerPasswordTokenGranter(authenticationManager, endpoints.getTokenServices(), clientDetailsService, endpoints.getOAuth2RequestFactory()));

        list.add(new RefreshTokenGranter(endpoints.getTokenServices(), clientDetailsService, endpoints.getOAuth2RequestFactory()));

        list.add(new AuthorizationCodeTokenGranter(endpoints.getTokenServices(), endpoints.getAuthorizationCodeServices(), clientDetailsService, endpoints.getOAuth2RequestFactory()));

        list.add(new ImplicitTokenGranter(endpoints.getTokenServices(), clientDetailsService, endpoints.getOAuth2RequestFactory()));

        //添加自定义的手机验证码模式
        list.add(getPhoneVerifyCodeTokenGranter(endpoints));

        list.add(new ClientCredentialsTokenGranter(endpoints.getTokenServices(), clientDetailsService, endpoints.getOAuth2RequestFactory()));

        return new CompositeTokenGranter(list);
    }

    private PhoneVerifyCodeTokenGranter getPhoneVerifyCodeTokenGranter(AuthorizationServerEndpointsConfigurer endpoints) {

        PhoneVerifyCodeDetailsAuthenticationProvider phoneVerifyCodeDetailsAuthenticationProvider = new PhoneVerifyCodeDetailsAuthenticationProvider();
        phoneVerifyCodeDetailsAuthenticationProvider.setUserDetailsService(phoneVerifyCodeUserDetailsService);
        phoneVerifyCodeDetailsAuthenticationProvider.setHideUserNotFoundExceptions(false);
        phoneVerifyCodeDetailsAuthenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder());

        return new PhoneVerifyCodeTokenGranter(authentication -> phoneVerifyCodeDetailsAuthenticationProvider.authenticate(authentication),
                endpoints.getTokenServices(), clientDetailsService, endpoints.getOAuth2RequestFactory());
    }

    @Bean
    public PhoneVerifyCodeUserDetailsService phoneVerifyCodeUserDetailsService() {
        return new PhoneVerifyCodeUserDetailsService();
    }
}
